package com.zwkj.util;

import cn.hutool.http.HttpUtil;
import com.zwkj.exception.InvalidArgument;
import com.zwkj.exception.InvalidToken;
import com.zwkj.pojo.vo.FileVo;
import com.zwkj.pojo.vo.UserQueryVo;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

public class RequestUtils {
    private RequestUtils() {
    }

    public static HttpServletRequest getCurrentRequest() {
        // #ServletUriComponentsBuilder.getCurrentRequest()
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
        return ((ServletRequestAttributes) attrs).getRequest();

    }

    public static String getWebOfficeToken(HttpServletRequest request) {
        final String token;
        if (Objects.isNull((token = request.getHeader("X-Weboffice-Token")))) {
            throw new InvalidToken("weboffice token is required");
        }
        return token;
    }

    public static String getAppId(HttpServletRequest request) {
        final String appId;
        if (Objects.isNull((appId = request.getHeader("X-App-Id")))) {
            throw new InvalidArgument("app id is required");
        }
        return appId;
    }

    public static String getRequestId(HttpServletRequest request) {
        final String requestId;
        if (Objects.isNull(requestId = request.getHeader("X-Request-Id"))) {
            return "";
        }
        return requestId;
    }

    public static String getUserQuery(HttpServletRequest request,String field) {
        final String userQuery;
        if (Objects.isNull(userQuery = request.getHeader("X-User-Query"))) {
            return null;
        }
        Map<String, String> map = HttpUtil.decodeParamMap(userQuery, StandardCharsets.UTF_8);
        String fieldStr = map.get(field);
        return fieldStr;
    }
}
